# <template>
  <div class="employee-list">
    <div class="header">
      <h2>员工管理</h2>
      <el-button type="primary" @click="openCreateDialog">
        <el-icon>
          <Plus />
        </el-icon>新增员工
      </el-button>
    </div>

    <div class="filter-section">
      <el-select v-model="selectedGroupId" placeholder="请选择车间" class="group-select" @change="handleGroupChange">
        <el-option label="显示所有" value="" />
        <el-option v-for="group in groups" :key="group.id" :label="group.name" :value="group.id" />
      </el-select>
    </div>

    <div class="employee-grid">
      <el-card v-for="employee in employees" :key="employee.id" class="employee-card"
        @click="showEmployeeDetail(employee)">
        <div class="employee-info">
          <el-avatar :size="64" :src="getAvatarUrl(employee.avatarHash)" @error="() => handleAvatarError(employee)">
            {{ employee.realName ? employee.realName.charAt(0).toUpperCase() : 'U' }}
          </el-avatar>
          <div class="info-content">
            <h3>{{ employee.realName }}</h3>
            <p class="group-name">{{ getGroupName(employee.groupId) || '未分配车间' }}</p>
            <p class="create-time">创建时间：{{ formatDate(employee.createTime) }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 员工详情抽屉 -->
    <el-drawer v-model="showDetailDrawer" title="员工详情" size="80%" :destroy-on-close="true">
      <template #default>
        <div class="employee-detail-content" v-if="currentEmployee">
          <!-- 基本信息卡片 -->
          <el-card class="detail-card">
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
              </div>
            </template>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">姓名：</span>
                <span class="value">{{ currentEmployee.realName }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户名：</span>
                <span class="value">{{ currentEmployee.username }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号：</span>
                <span class="value">{{ currentEmployee.phone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="label">所属车间：</span>
                <span class="value">{{ getGroupName(currentEmployee.groupId) }}</span>
              </div>
            </div>
          </el-card>

          <!-- 功能卡片 -->
          <el-card class="detail-card">
            <template #header>
              <div class="card-header">
                <span>相关操作</span>
              </div>
            </template>
            <div class="action-grid">
              <el-button type="primary" @click="showWorkRecords">
                <el-icon>
                  <Document />
                </el-icon>工作记录
              </el-button>
              <el-button type="success" @click="showAttendance">
                <el-icon>
                  <Calendar />
                </el-icon>考勤记录
              </el-button>
              <el-button type="warning" @click="resetPassword">
                <el-icon>
                  <Key />
                </el-icon>重置密码
              </el-button>
              <el-button type="info" @click="handleChangeAvatar">
                <el-icon>
                  <Picture />
                </el-icon>修改头像
              </el-button>
              <el-button type="danger" @click="handleDeleteEmployee">
                <el-icon>
                  <Delete />
                </el-icon>删除员工
              </el-button>
            </div>
          </el-card>
        </div>
      </template>
    </el-drawer>

    <!-- 新增员工对话框 -->
    <el-dialog v-model="showCreateDialog" title="新增员工" width="90%" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" class="create-form">
        <!-- 头像上传 -->
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :auto-upload="false" @change="handleAvatarChange">
            <el-avatar v-if="form.avatar" :size="80" :src="avatarPreview" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" />
        </el-form-item>
        <el-form-item label="所属车间" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择车间">
            <el-option v-for="group in groups" :key="group.id" :label="group.name" :value="group.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreate">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工作记录抽屉 -->
    <el-drawer v-model="showWorkRecordsDrawer" title="工作记录" size="90%" :with-header="false">
      <work-records-view v-if="showWorkRecordsDrawer && currentEmployee" :employee="currentEmployee"
        @close="showWorkRecordsDrawer = false" />
    </el-drawer>

    <!-- 考勤记录抽屉 -->
    <el-drawer v-model="showAttendanceDrawer" title="考勤记录" size="90%" :with-header="false">
      <attendance-view v-if="showAttendanceDrawer && currentEmployee" :employee="currentEmployee"
        @close="showAttendanceDrawer = false" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Document, Calendar, Key, Picture } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { fetchGroups } from '@/api/groups'
import {
  getAllUsers,
  getUsersByGroup,
  createUser,
  deleteUser,
  resetUserPassword
} from '@/api/employees'
import WorkRecordsView from './components/WorkRecordsView.vue'
import AttendanceView from './components/AttendanceView.vue'
import { uploadUserAvatar } from '@/api/user'

// 定义接口
interface Employee {
  id: number
  username: string
  realName: string
  groupId: number
  phone: string
  remark: string
  avatarHash?: string
  createTime: string
}

interface Group {
  id: number
  name: string
  type: number
}

interface FormData {
  username: string
  password: string
  realName: string
  groupId: string | number
  phone: string
  remark: string
  avatar: File | null
}

const router = useRouter()

// 状态
const employees = ref<Employee[]>([])
const groups = ref<Group[]>([])
const selectedGroupId = ref<string | number>('')
const showDetailDrawer = ref(false)
const showCreateDialog = ref(false)
const showWorkRecordsDrawer = ref(false)
const showAttendanceDrawer = ref(false)
const currentEmployee = ref<Employee | null>(null)
const isCreating = ref(false)
const formRef = ref()
const form = ref<FormData>({
  username: '',
  password: '',
  realName: '',
  groupId: '',
  phone: '',
  remark: '',
  avatar: null
})

// 头像预览
const avatarPreview = ref('')

// 头像上传相关
const avatarInput = ref<HTMLInputElement | null>(null)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 获取头像URL
const getAvatarUrl = (hash: string | undefined) => {
  if (!hash) return ''
  const baseUrl = import.meta.env.VITE_BASE_URL || 'http://localhost:8080'
  return `${baseUrl}/api/avatar/${hash}`
}

// 处理头像加载错误
const handleAvatarError = (employee) => {
  console.error('头像加载失败:', employee.username)
}

// 获取车间名称
const getGroupName = (groupId) => {
  if (!groupId) return '未分配'
  const group = groups.value.find(g => g.id === groupId)
  return group ? group.name : '未分配'
}

// 获取员工列表
const fetchEmployees = async () => {
  try {
    let res
    if (selectedGroupId.value || selectedGroupId.value === 0) {
      res = await getUsersByGroup(Number(selectedGroupId.value))
    } else {
      res = await getAllUsers()
    }
    if (res.code === 200) {
      employees.value = res.data
    } else {
      ElMessage.error(res.message || '获取员工列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取员工列表失败')
  }
}

// 获取车间列表
const fetchGroupList = async () => {
  try {
    const res = await fetchGroups()
    if (res.code === 200) {
      // 只显示普通车间（type=1）
      groups.value = res.data.filter(group => group.type != 2)
    }
  } catch (error) {
    ElMessage.error('获取车间列表失败')
  }
}

// 显示员工详情
const showEmployeeDetail = (employee) => {
  currentEmployee.value = employee
  showDetailDrawer.value = true
}

// 打开新增对话框
const openCreateDialog = () => {
  form.value = {
    username: '',
    password: '',
    realName: '',
    groupId: '',
    phone: '',
    remark: '',
    avatar: null
  }
  showCreateDialog.value = true
}

// 头像上传前的验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 处理头像变更
const handleAvatarChange = (file: { raw: File }) => {
  form.value.avatar = file.raw
  avatarPreview.value = URL.createObjectURL(file.raw)
}

// 创建员工
const handleCreate = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 先创建用户
    const createRes = await createUser({
      username: form.value.username,
      password: form.value.password,
      realName: form.value.realName,
      groupId: form.value.groupId,
      phone: form.value.phone,
      remark: form.value.remark
    })

    if (createRes.code === 200) {
      // 如果有头像，上传头像
      if (form.value.avatar) {
        const avatarRes = await uploadUserAvatar(createRes.data.id, form.value.avatar)
        if (avatarRes.code !== 200) {
          ElMessage.warning('用户创建成功，但头像上传失败')
        }
      }

      ElMessage.success('创建成功')
      showCreateDialog.value = false
      fetchEmployees()
    } else {
      throw new Error(createRes.message || '创建失败')
    }
  } catch (error) {
    console.error('创建员工失败:', error)
    ElMessage.error(error.message || '创建失败')
  }
}

// 重置密码
const resetPassword = async () => {
  try {
    await ElMessageBox.confirm('确定要重置该员工的密码吗？')
    const res = await resetUserPassword(currentEmployee.value.id, { newPassword: '123456' })
    if (res.code === 200) {
      ElMessage.success('密码重置成功')
    } else {
      ElMessage.error(res.message || '密码重置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败')
    }
  }
}

// 删除员工
const handleDeleteEmployee = async () => {
  try {
    await ElMessageBox.confirm('确定要删除该员工吗？此操作不可恢复！')
    const res = await deleteUser(currentEmployee.value.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      showDetailDrawer.value = false
      fetchEmployees()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 显示工作记录
const showWorkRecords = () => {
  showWorkRecordsDrawer.value = true
}

// 显示考勤记录
const showAttendance = () => {
  showAttendanceDrawer.value = true
}

// 处理车间选择变化
const handleGroupChange = () => {
  fetchEmployees()
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 编辑员工
const editEmployee = () => {
  if (!currentEmployee.value) return
  router.push(`/employee/Detail/${currentEmployee.value.id}`)
}

// 处理修改头像
const handleChangeAvatar = () => {
  // 创建一个隐藏的文件输入框
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.style.display = 'none'

  input.onchange = async (e: Event) => {
    const target = e.target as HTMLInputElement
    const file = target.files?.[0]

    if (!file) return

    // 验证文件
    const isValid = beforeAvatarUpload(file)
    if (!isValid) return

    try {
      // 上传头像
      const res = await uploadUserAvatar(currentEmployee.value.id, file)
      if (res.code === 200) {
        // 更新当前员工的头像哈希
        currentEmployee.value.avatarHash = res.data.avatarHash
        ElMessage.success('头像修改成功')
        // 重新获取员工列表以更新界面
        fetchEmployees()
      }
    } catch (error) {
      console.error('上传头像失败:', error)
      ElMessage.error('上传头像失败')
    }
  }

  // 触发文件选择
  input.click()
}

onMounted(() => {
  fetchEmployees()
  fetchGroupList()
})
</script>

<style scoped>
.employee-list {
  padding: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h2 {
  margin: 0;
}

.filter-section {
  margin-bottom: 24px;
}

.group-select {
  width: 100%;
}

.employee-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.employee-card {
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.employee-info {
  display: flex;
  gap: 16px;
}

.info-content {
  flex: 1;
}

.info-content h3 {
  margin: 0 0 8px;
  font-size: 16px;
}

.group-name {
  margin: 0 0 4px;
  color: #666;
  font-size: 14px;
}

.create-time {
  margin: 0;
  color: #999;
  font-size: 12px;
}

.employee-detail-content {
  padding: 16px;
}

.detail-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  gap: 8px;
}

.info-item .label {
  color: #666;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

:deep(.el-drawer__body) {
  padding: 0;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader-icon:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
}

:deep(.el-upload) {
  cursor: pointer;
}
</style>